package com.moli.lumpSugar.websocket;

import cn.hutool.core.net.url.UrlBuilder;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpRequest;
import com.moli.lumpSugar.websocket.util.NettyUtil;

import java.util.Optional;

/**
 * Description: 用protocols传参实现握手认证
 * Author: zhangjt
 * Date: 2024-10-30
 */
public class MyHandShakeByUrlHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof HttpRequest) {
            final HttpRequest req = (HttpRequest) msg;
            UrlBuilder urlBuilder = UrlBuilder.ofHttp(req.getUri());
            Optional<String> tokenOptional = Optional.of(urlBuilder)
                    .map(UrlBuilder::getQuery)
                    .map(k -> k.get("token"))
                    .map(CharSequence::toString);
            tokenOptional.ifPresent(s -> NettyUtil.setAttribute(ctx.channel(), NettyUtil.TOKEN, s));
            // 这里要将 url中的token参数去掉，否则再netty的WebSocketServerProtocolHandler处理器中，因为传入的url地址和本来配置的url地址‘/’不一致，导致不发送事件，无法走到自定义的handler处理器处理认证逻辑
            req.setUri(urlBuilder.getPathStr());
        }
        ctx.fireChannelRead(msg);
    }
}

